//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    selectImgs: null,
    imgurl: app.urlimg,
    isAll: true,
    allImg: "/pages/icon/checkMsg1.png",
    allPrice: 0.00,
    edits: [],
    tmpData: [],
    loadHidden: false,
    loadText: "加载中...",
    modality_modal: false,
    // 右拉删除事件
    startX: 0, //开始坐标
    startY: 0,
    right_delet: [],
    canAccount: true,
    failGoods: null
  },
  onLoad: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var h = res.screenHeight - 112;
        h = h + "px";
        that.setData({
          screenHeight: h,
        })
      }
    })


    app.app_load(load_fn);//用户登录
    function load_fn() {
      wx.showLoading({
        title: '加载中...',
        mask: true,
      });


      var selectImgs = [];
      var edits = [];
      var right_delet = [];
      wx.request({
        url: app.url + 'api_order/cart',
        data: {},
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key'),
        }, success: function (json) {
          wx.hideLoading();
          if (json.data.done == true) {
            var allPrice = 0
            for (var i = 0; i < json.data.result.length; i++) {
              if (parseInt(json.data.result[i].number) <= parseInt(json.data.result[i].store_nums)) {
                json.data.result[i].isAccount = false;
                selectImgs.push(
                  "/pages/icon/checkMsg1.png"
                )
                allPrice += parseFloat(json.data.result[i].price) * parseInt(json.data.result[i].number)
              } else {
                json.data.result[i].isAccount = true;
                if (parseInt(json.data.result[i].store_nums) == 0 || parseInt(json.data.result[i].store_nums) < parseInt(json.data.result[i].number)) {
                  console.log(5555555);
                  json.data.result[i].isAccount_title = '商品库存不足';
                } else if (json.data.result[i].is_del != 0) {
                  json.data.result[i].isAccount_title = '宝贝已不能购买，请联系店长';
                }
                selectImgs.push(
                  "/pages/icon/checkMsg.png"
                )
              }

              // 修改数量
              edits.push(
                false
              )
              // 右拉删除
              right_delet.push(
                false
              )
            }
            that.setData({
              selectImgs: selectImgs,
              edits: edits,
              tmpData: json.data.result,
              allPrice: allPrice,
              loadHidden: true,
              right_delet: right_delet,
              canAccount: that.data.canAccount
            })
          } else {
            app.apperror(json);
          }
        }
      })


      //猜你喜欢
      wx.request({
        url: app.url + 'api_footprint/footprint_group_list',
        data: {
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        },
        success: function (json) {
          that.setData({
            likegoods: json.data.result,
          })
        }
      })
    }
  },

  // 猜你喜欢列表
  click_goods: function (e) {
    wx.navigateTo({
      url: '/pages/index/detail/index?id=' + e.currentTarget.id,
    })
  },
  // 响应全选事件
  allTap: function () {

    var that = this;
    // 调用全选方法
    allSelectGoods(this);

  },

  l_home: function (e) {
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  // 
  l_cate: function (e) {
    wx.redirectTo({
      url: '/pages/category/index'
    })
  },

  l_cart: function (e) {
    wx.redirectTo({
      url: '/pages/shop/index'
    })
  },
  l_account: function (e) {
    wx.redirectTo({
      url: '/pages/account/index'
    })
  },
  goodslink: function (e) {

    wx.navigateTo({
      url: '/pages/index/detail/index?id=' + e.currentTarget.id,
    })
  },
  
  // 响应删除
  deleteGoods: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '商品删除，不可恢复！',
      success: function (res) {
        if (res.confirm) {
          var cid = e.currentTarget.id;


          //del_cart?cart_id=5&number=5
          wx.request({
            url: app.url + 'api_order/del_cart',
            data: {
              'cart_id': e.currentTarget.dataset.cid
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            }, success: function (json) {
              // 删除当前商品
              var goodsData = that.data.tmpData;
              goodsData.splice(cid, 1);
              var edits = that.data.edits;
              var checkMsg1 = "/pages/icon/checkMsg1.png";
              edits.splice(cid, 1);
              var selectImgs = that.data.selectImgs;
              selectImgs.splice(cid, 1);
              var allPrice = 0;
              for (var i = 0; i < selectImgs.length; i++) {
                if (selectImgs[i] == checkMsg1) {
                  var price = that.data.tmpData[i].price;
                  var number = that.data.tmpData[i].number;
                  allPrice += price * number;
                }
              }
              that.setData({
                allPrice: allPrice,
                tmpData: goodsData,
                edits: edits,
                selectImgs: selectImgs,
              })
            }
          })
        }
      }
    })
  },



  // 响应选择商品
  selectGoodsTap: function (e) {
    var that = this;
    var id = e.currentTarget.id;
    //  调用单一商品选择
    var res = selectGoods(this, e, 'selected');
    that.data.edits[id] = false
    that.setData({
      selectImgs: res.selectImgs,
      allPrice: res.allPrice,
      allImg: res.allImg,
      edits: that.data.edits,
    })
  },

  // 响应编辑按钮
  editTap: function (e) {
    var that = this
    var res = selectGoods(this, e, 'edit');
    that.data.selectImgs = res.selectImgs
    var that = this;
    var cid = e.currentTarget.id;

    // 判断是否选中商品
    /*  if(that.data.selectImgs[cid] ==  "/pages/icon/checkMsg.png") {
      that.data.selectImgs[cid]="/pages/icon/checkMsg1.png"
          }*/

    //  调用单一商品选择

    /*wx.showModal({
      title: '提示',
      content: '亲，选中商品才可以编辑噢~',
      
    })
    return;*/



    var edits = that.data.edits;
    for (var i = 0; i < edits.length; i++) {
      if (cid == i) edits[i] == true ? edits[i] = false : edits[i] = true;
    }
    console.log(edits);
    that.setData({ edits: edits, selectImgs: that.data.selectImgs, allPrice: res.allPrice });
  },

  // 响应数量选择 加一
  addNum: function (e) {
    var that = this;
    var i = e.currentTarget.id;
    var goodsData = that.data.tmpData;
    var goods = goodsData[i];
    var selectImgs = that.data.selectImgs;

    if (parseInt(goods.number) < parseInt(that.data.tmpData[i].store_nums)) {
      goods.number = parseInt(goods.number) + 1;
      goodsData[i] = goods;

      var allPrice = parseFloat(that.data.allPrice);
      //  价钱加1
      if (selectImgs[i] == '/pages/icon/checkMsg1.png') {
        allPrice += parseInt(goods.price);
        allPrice = String(allPrice);
      }
      var re = /([0-9]+.[0-9]{2})[0-9]*/;


      //到接口更新数量api_order/edit_cart_number?cart_id=5&number=5 
      console.log(e.target.dataset.cid);
      wx.request({
        url: app.url + 'api_order/edit_cart_number',
        data: {
          'cart_id': e.target.dataset.cid,
          number: goods.number
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {
          // 原代码
          // that.setData({
          //     tmpData: goodsData,
          //     allPrice: allPrice.replace(re, "$1"),
          // });
          //weiki 修改部分开始
          if (json.data.done) {
            that.setData({
              tmpData: goodsData,
              allPrice: (selectImgs[i] == '/pages/icon/checkMsg1.png' ? allPrice.replace(re, "$1") : allPrice),
            });
          } else {
            goodsData[i].number = goodsData[i].number - 1;
            that.setData({
              tmpData: goodsData,
            });
            wx.showModal({
              title: '提示',
              content: json.data.message,
            })
          }
          //weiki 修改结束
        }
      })

    } else {
      //提示信息
      wx.showToast({
        title: '已达最大库存',  //标题  
        icon: 'loading',
        duration: 1500,
      })
    }
  },


  // 减一
  cutNum: function (e) {
    var that = this;
    var i = e.currentTarget.id;
    var goodsData = that.data.tmpData;
    var goods = goodsData[i];
    var selectImgs = that.data.selectImgs;

    goods.number = parseInt(goods.number)
    if (goods.number > 1) {
      goods.number = goods.number - 1;
      goodsData[i] = goods;
      //  价钱减1
      var allPrice = parseFloat(that.data.allPrice);
      if (selectImgs[i] == '/pages/icon/checkMsg1.png') {
        allPrice -= goods.price;
        allPrice = String(allPrice);
      }
      var re = /([0-9]+.[0-9]{2})[0-9]*/;

      wx.request({
        url: app.url + 'api_order/edit_cart_number',
        data: {
          'cart_id': e.target.dataset.cid,
          number: goods.number
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {
          that.setData({
            tmpData: goodsData,
            allPrice: (selectImgs[i] == '/pages/icon/checkMsg1.png' ? allPrice.replace(re, "$1") : allPrice),
          });
        }
      })




    }
  },
  // 响应结算按钮被单击
  accountsTAP: function (e) {
    var that = this
    var cart_id = '';
    console.log(that.data.tmpData);
    console.log(that.data.selectImgs);
    for (var i = 0; i < that.data.selectImgs.length; i++) {
      if (that.data.selectImgs[i] == '/pages/icon/checkMsg1.png') {
        cart_id += that.data.tmpData[i].id + ','
      }
    }
    if (cart_id !== '') {
      var lastIndex = cart_id.lastIndexOf(',');
      if (lastIndex > -1) {
        cart_id = cart_id.substring(0, lastIndex);
      }
      wx.navigateTo({ url: '/pages/index/detail/orderDetail/index?actionType=cart&cart_id=' + cart_id })
    } else {
      wx.showModal({
        title: '提示',
        content: '您未选中商品~',
      })
    }

  },


  //产品样式选择
  products: function (e) {
    var that = this;
    var index = e.currentTarget.id;
    var tmpData = that.data.tmpData;
    console.log(tmpData);


    var modality_modal = that.data.modality_modal;
    if (modality_modal == true) {
      modality_modal = false;
    } else {
      modality_modal = true;
    }
    that.setData({
      modality_modal: modality_modal,
    })
  },
  /****************************************************** 右拉删除功能 ********/
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    console.log("手指触摸动作开始");
    //开始触摸时 重置所有删除
    var right_delet = this.data.right_delet;
    for (var i = 0; i < right_delet.length; i++) {
      right_delet[i] = false;
    }

    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      right_delet: right_delet,
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    console.log("滑动事件处理");
    var that = this;
    var index = e.currentTarget.dataset.index;//当前索引
    var startX = that.data.startX;//开始X坐标
    var startY = that.data.startY;//开始Y坐标
    var touchMoveX = e.changedTouches[0].clientX;//滑动变化坐标
    var touchMoveY = e.changedTouches[0].clientY;//滑动变化坐标
    //获取滑动角度
    var angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    var right_delet = that.data.right_delet;

    that.data.right_delet.forEach(function (v, i) {
      v = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v = false
        else //左滑
          v = true
        right_delet[index] = v;
      }
    })

    //更新数据
    that.setData({
      right_delet: that.data.right_delet,
    })
  },
	/**
	 * 计算滑动角度
	 * @param {Object} start 起点坐标
	 * @param {Object} end 终点坐标
	 */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },


  /* 响应收藏按钮 *********************************************************************/
  collect: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;//当前索引
    var goods_id = that.data.tmpData[index].goods_id;
    wx.request({
      url: app.url + 'api_goods/favorite_add',
      data: {
        goods_id: goods_id,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (res) {
        console.log(res.data.result.message);
        wx.showToast({
          title: res.data.result.message,  //标题  
          icon: 'success',  //图标，支持"success"、"loading"   
          duration: 1200, //提示的延迟时间，单位毫秒，默认：1500
        })
      }
    })
  },


  autoFormId: function (e) {
    wx.request({
      url: app.url + "api_team/collectFormId",
      data: {
        formId: e.detail.formId
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (result) { }
    });
  },
  //分享
  onShareAppMessage: function () {

  },
})

/*********  单商品选择功能 *********/
function selectGoods(that, e, type) {
  var cid = e.currentTarget.id;
  var selectImgs = that.data.selectImgs;
  var checkMsg = "/pages/icon/checkMsg.png";
  var checkMsg1 = "/pages/icon/checkMsg1.png";//选中
  var allImg = '';
  console.log(selectImgs);
  if (type == 'edit') {
    selectImgs[cid] = checkMsg1
  } else {
    selectImgs[cid] = selectImgs[cid] == checkMsg ? checkMsg1 : checkMsg;
    var all_selec = 0;
    for (var i = 0; i < selectImgs.length; i++) {
      if (selectImgs[i] == checkMsg1) {
        ++all_selec;
      }
    }
    if (all_selec == selectImgs.length) {
      allImg = checkMsg1;
    } else {
      allImg = checkMsg;
    }
  }
  var allPrice = 0;
  for (var i = 0; i < selectImgs.length; i++) {
    if (selectImgs[i] == checkMsg1) {
      var price = that.data.tmpData[i].price;
      var number = that.data.tmpData[i].number;
      allPrice += price * number;
    }
  }
  var re = /([0-9]+.[0-9]{2})[0-9]*/;
  allPrice = String(allPrice);
  allPrice = allPrice.replace(re, "$1")
  var res = { selectImgs: selectImgs, allPrice: allPrice, allImg: allImg }
  return res


  /*for(var i= 0; i < selectImgs.length; i++){
    if(i == cid) {
       var selectImg = selectImgs[i];
       if(type=='edit'){
         selectImgs[i] = checkMsg1
       }else{
        selectImg == checkMsg ? selectImgs[i] = checkMsg1 : selectImgs[i] = checkMsg; 
       }
       // 计算价钱
       var price = that.data.tmpData[i].price;
       var number = that.data.tmpData[i].number;
       var tmpPrice = price * number;

       tmpPrice = checkMsg == selectImgs[i] ? -tmpPrice : tmpPrice;
       allPrice = allPrice + tmpPrice;
    } 
   }*/



}


/*********  实现全选功能 ***********/
function allSelectGoods(that) {

  that.setData({
    isAll: !that.data.isAll,
  })

  var checkMsg = "/pages/icon/checkMsg.png";
  var checkMsg1 = "/pages/icon/checkMsg1.png";

  var selectImgs = that.data.selectImgs;
  var allPrice = parseFloat(that.data.allPrice);
  var goods_data = that.data.tmpData;//获取全部商品

  if (that.data.isAll) {

    allPrice = 0.00;
    for (var i = 0; i < selectImgs.length; i++) {
      if (!goods_data[i].isAccount) {
        var selectImg = selectImgs[i];
        selectImgs[i] = checkMsg1;

        // 计算价钱
        var price = that.data.tmpData[i].price;
        var number = that.data.tmpData[i].number;
        allPrice += price * number;
      }
    }

  } else {
    for (var i = 0; i < selectImgs.length; i++) {

      var selectImg = selectImgs[i];
      selectImgs[i] = checkMsg;
    }

    allPrice = 0.00;
  }

  var re = /([0-9]+.[0-9]{2})[0-9]*/;
  allPrice = String(allPrice);

  console.log(selectImgs);
  that.setData({
    allImg: that.data.isAll == true ? checkMsg1 : checkMsg,
    selectImgs: selectImgs,
    allPrice: allPrice.replace(re, "$1"),
  })

}

